//
//  BITabBarVC.m
//  BIProjectModule
//
//  Created by yown on 2022/2/16.
//

#import "BITabBarVC.h"
#import "BITabModel.h"
#import "BITabBarView.h"
#import "BIProjectContext.h"

#import <BINetworkModule/BINetworkManager.h>
#import <BIRouteModule/BIRouteManager.h>

#import <YYNavigation/YYNavigation.h>

@interface BITabBarVC ()

@property (nonatomic) BITabBarView *tabBarView;
@property (nonatomic) BITabModel *tabBarModel;

@end

@implementation BITabBarVC

#pragma mark - LifeCycle

- (instancetype)init {
    self = [super init];
    if (self) {
        // 设置基本的view
        [self bi_setupView];
        // 先使用本地数据
        [self bi_setupData];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(languageChanged:) name:BINotificationNameChangeLanguage object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Setup

- (void)bi_setupData {
    self.tabBarModel = [BITabModel loadFromLocal];
    if (!self.tabBarModel) {
        self.tabBarModel = [BITabModel new];
    }
    [self bi_setupSubVC];
}

- (void)bi_setupView {
    self.view.backgroundColor = [UIColor whiteColor];
    self.tabBar.backgroundImage = [UIImage new];
    self.tabBar.shadowImage = [UIImage new];
    @weakify(self);
    self.tabBarView = [[BITabBarView alloc] initWithFrame:self.tabBar.bounds clickBlock:^(BITabItemModel *itemModel) {
        @strongify(self);
        NSUInteger index = [self.tabBarModel.useTabArray indexOfObject:itemModel];
        [self selectVCWithIndex:index];
    }];
    self.tabBarView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.tabBar addSubview:self.tabBarView];
}

- (void)bi_setupSubVC {
    // 创建子VC
    NSMutableArray *vcArray = [NSMutableArray array];
    [self.tabBarModel.useTabArray enumerateObjectsUsingBlock:^(BITabItemModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIViewController *vc = [[BIRouteManager sharedInstance] queryVCURL:obj.itemLink arguments:nil];
        vc.hidesBottomBarWhenPushed = NO;
        YYNavigationController *navigationVC = [[YYNavigationController alloc] initWithRootViewController:vc];
        [vcArray addObject:navigationVC];
        vc.yy_navigationItem.title = obj.itemName;
    }];
    // 更新子VC
    self.viewControllers = [vcArray copy];
    // 每次赋值完子vc后，将自定义的tabbar移到最前面
    [self.tabBar bringSubviewToFront:self.tabBarView];
    // 创建tabbaritem，并默认选中第一个
    self.selectedIndex = 0;
    self.tabBarModel.useTabArray.firstObject.isSelected = YES;
    [self.tabBarView refreshTabBar:self.tabBarModel.useTabArray isFocus:YES];
}

#pragma mark - Public Method

- (void)refreshTabBarController {
//    NSString *path = @"sso-gateway/lsgc/menu/getUserTab.do";
//    NSDictionary *arguments = @{@"appCode" : @"retailapp", @"loginSourceCode" : @"loginSourceCode"};
//    BINetworkRequest *request = [[BINetworkManager sharedInstance] requestWithPath:path arguments:arguments succeedBlock:nil failureBlock:nil completionBlock:^(BINetworkResponse *response) {
//        // 成功使用网络请求的数据，失败使用默认数据
//        BITabModel *tempModel = [response.modelValue isKindOfClass:[BITabModel class]] ? response.modelValue : [BITabModel new];
//        // 判断刷新后的数据和刷新前不相同，则重新构造子视图
//        if ([self bi_checkModelIsDifferent:tempModel model2:self.tabBarModel]) {
//            // 存储不同的数据，并更新到本地
//            self.tabBarModel = tempModel;
//            [self.tabBarModel saveSelfToLocal];
//            // 添加子VC
//            [self bi_setupSubVC];
//        }
//    }];
//    request.methodType = kBINetworkGetMethodType;
//    request.successCodeSet = [NSSet setWithObjects:@"0", @"1001", @"2000000", nil];
//    request.codeKeyPath = @"errorCode";
//    request.responseKeyPath = @"data";
//    request.responseClass = [BITabModel class];
//    [[BINetworkManager sharedInstance] startRequest:request];
}

- (void)selectVCWithIndex:(NSUInteger)index {
    [self.tabBarModel.useTabArray enumerateObjectsUsingBlock:^(BITabItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx == index) {
            obj.isSelected = YES;
            self.selectedIndex = idx;
        } else {
            obj.isSelected = NO;
        }
    }];
    // 刷新tabbar状态
    [self.tabBarView refreshTabBar:self.tabBarModel.useTabArray isFocus:NO];
}

#pragma mark - Notification

- (void)languageChanged:(NSNotification *)notification {
    self.tabBarModel.originalTabArray = nil;
    [self.tabBarView refreshTabBar:self.tabBarModel.useTabArray isFocus:NO];
}

#pragma mark - Private Method

- (BOOL)bi_checkModelIsDifferent:(BITabModel *)model1 model2:(BITabModel *)model2 {
    // 任意一个model不存在，即为有变化
    if (!model1 || !model2) {
        return YES;
    }
    // 两个model列表个数不同，即为有变化
    if (model1.useTabArray.count != model2.useTabArray.count) {
        return YES;
    }
    BOOL different = NO;
    // 如果每一个数组的元素有任意一项不同，即为有变化
    for (NSUInteger i = 0; i < model1.useTabArray.count; i++) {
        BITabItemModel *itemModel1 = [model1.useTabArray objectAtIndex:i];
        BITabItemModel *itemModel2 = [model2.useTabArray objectAtIndex:i];
        if (![itemModel1.itemCode isEqualToString:itemModel2.itemCode] ||
            ![itemModel1.itemName isEqualToString:itemModel2.itemName] ||
            ![itemModel1.itemNormalImage isEqualToString:itemModel2.itemNormalImage] ||
            ![itemModel1.itemSelectedImage isEqualToString:itemModel2.itemSelectedImage] ||
            ![itemModel1.itemLink isEqualToString:itemModel2.itemLink]) {
            different = YES;
            break;
        }
    }
    return different;
}

@end
